import { defineStore } from 'pinia';
import type { LoginUser } from '@/index.d';
import { getMenuTitleListByUserId, getPermissionTextListByUserId, api } from '@/index';
import { ElMessage, type FormInstance } from 'element-plus';
import { stringify } from 'qs';
import router from '@/router';

export const loginData = reactive({
  username: 'yinhongqi',
  password: 'admin12345678'
});

export const useLoginUserStore = defineStore(
  'useLoginUserStore',
  () => {
    const loginUser = reactive<LoginUser>({
      permissions: [],
      menus: []
    });

    const fileUploadHeader = reactive({ Authorization: '' });

    const setMenus = async (userId: number) => {
      const menuList = await getMenuTitleListByUserId(userId);
      menuList.forEach((menu: string) => {
        loginUser.menus?.push(menu);
      });
    };

    const setPermissions = async (userId: number) => {
      const permissionList = await getPermissionTextListByUserId(userId);
      permissionList.forEach((permission: string) => {
        loginUser.permissions?.push(permission);
      });
    };

    const setLoginUser = async (value: LoginUser) => {
      loginUser.id = value.id;
      loginUser.username = value.username;
      loginUser.name = value.name;
      loginUser.workNo = value.workNo;
      loginUser.token = value.token;
      loginUser.departmentId = value.departmentId;
      loginUser.department = value.department;
      fileUploadHeader.Authorization = value.token as string;
      await setMenus(value.id as number);
      await setPermissions(value.id as number);
    };

    const resetLoginUser = () => {
      loginUser.menus = [];
      loginUser.permissions = [];
      delete loginUser.id;
      delete loginUser.username;
      delete loginUser.name;
      delete loginUser.workNo;
      delete loginUser.token;
      delete loginUser.departmentId;
      delete loginUser.department;
      delete loginUser.menus;
      delete loginUser.permissions;
    };

    const login = async (formEl: FormInstance | undefined | any) => {
      const { setLoginUser } = useLoginUserStore();
      if (!formEl) return;
      formEl.validate(async (valid: any) => {
        if (valid) {
          try {
            const res = await api({
              method: 'post',
              url: '/auth/login',
              data: stringify(loginData)
            });
            if (res.status === 200) {
              if (res.data.status) {
                ElMessage({
                  type: res.data.type,
                  message: res.data.msg
                });
                await setLoginUser(res.data.body);
                router.replace('/');
              } else {
                ElMessage({
                  type: res.data.type,
                  message: res.data
                });
              }
            } else {
              ElMessage.error('获取失败，错误信息是：' + res.statusText);
            }
          } catch (error) {
            ElMessage.error('获取失败，错误信息是：' + error);
            return false;
          }
        }
      });
    };

    const logout = async (username: string) => {
      const { resetLoginUser } = useLoginUserStore();
      try {
        const res = await api({
          method: 'get',
          url: '/auth/logout/' + username
        });
        if (res.status === 200) {
          if (res.data.status) {
            ElMessage({
              type: res.data.type,
              message: res.data.msg
            });
            resetLoginUser();
            sessionStorage.clear();
            router.push('/login');
            router.go(0);
          } else {
            ElMessage({
              type: res.data.type,
              message: res.data
            });
          }
        } else {
          ElMessage.error('获取失败，错误信息是：' + res.statusText);
        }
      } catch (error) {
        ElMessage.error('获取失败，错误信息是：' + error);
        return false;
      }
    };

    return {
      loginUser,
      setLoginUser,
      resetLoginUser,
      login,
      logout,
      fileUploadHeader
    };
  },
  { persist: true }
);
